#!/usr/bin/env python3
"""
安全工具使用示例

本示例演示如何在项目中使用新的安全工具集，包括：
- SecurityValidator: 验证命令、路径和输入数据的安全性
- PermissionChecker: 检查文件权限和管理员权限
- SensitiveDataHandler: 处理敏感数据（密码生成、哈希、掩码等）
- SecureCommandExecutor: 安全执行系统命令
- security_audit: 对目录进行安全审计
"""

import os
import sys
import tempfile

# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from core.security_utils import (
    SecurityValidator,
    PermissionChecker,
    SensitiveDataHandler,
    SecureCommandExecutor,
    security_audit
)

def demo_security_validator():
    """演示SecurityValidator的使用"""
    print("=== SecurityValidator 演示 ===")
    
    # 命令验证
    safe_commands = ["ls -la", "pwd", "whoami"]
    dangerous_commands = ["rm -rf /", "format c:", "shutdown -h now"]
    
    print("\n1. 命令安全验证:")
    for cmd in safe_commands:
        result = SecurityValidator.validate_command(cmd)
        print(f"  '{cmd}' -> {'安全' if result else '危险'}")
    
    for cmd in dangerous_commands:
        result = SecurityValidator.validate_command(cmd)
        print(f"  '{cmd}' -> {'安全' if result else '危险'}")
    
    # 路径验证
    print("\n2. 路径安全验证:")
    safe_paths = ["/home/user/documents", "C:\\Users\\user\\Documents"]
    dangerous_paths = ["/etc/passwd", "../../../etc/shadow", "/proc/1/mem"]
    
    for path in safe_paths + dangerous_paths:
        result = SecurityValidator.validate_path(path)
        print(f"  '{path}' -> {'安全' if result else '危险'}")
    
    # 输入验证
    print("\n3. 输入数据验证:")
    safe_inputs = ["normal text", "user@example.com", "Hello World!"]
    dangerous_inputs = ["<script>alert('xss')</script>", "'; DROP TABLE users; --", "$(rm -rf /)"]
    
    for inp in safe_inputs + dangerous_inputs:
        result = SecurityValidator.validate_input(inp)
        print(f"  '{inp}' -> {'安全' if result else '危险'}")

def demo_permission_checker():
    """演示PermissionChecker的使用"""
    print("\n=== PermissionChecker 演示 ===")
    
    # 检查管理员权限
    print("\n1. 管理员权限检查:")
    is_admin = PermissionChecker.check_root_required()
    print(f"  当前用户是否为管理员: {'是' if is_admin else '否'}")
    
    # 创建临时文件并检查权限
    print("\n2. 文件权限检查:")
    with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
        tmp_file.write(b"test content")
        tmp_path = tmp_file.name
    
    try:
        perms = PermissionChecker.check_file_permissions(tmp_path)
        if 'error' not in perms:
            print(f"  文件: {tmp_path}")
            print(f"  权限模式: {perms['octal']}")
            print(f"  所有者可读: {perms['owner_read']}")
            print(f"  所有者可写: {perms['owner_write']}")
            print(f"  所有者可执行: {perms['owner_execute']}")
            if perms['warnings']:
                print(f"  安全警告: {', '.join(perms['warnings'])}")
        else:
            print(f"  检查失败: {perms['error']}")
    finally:
        try:
            os.unlink(tmp_path)
        except:
            pass

def demo_sensitive_data_handler():
    """演示SensitiveDataHandler的使用"""
    print("\n=== SensitiveDataHandler 演示 ===")
    
    # 生成安全密码
    print("\n1. 安全密码生成:")
    for length in [8, 12, 16]:
        password = SensitiveDataHandler.generate_secure_password(length)
        print(f"  {length}位密码: {password}")
    
    # 密码哈希
    print("\n2. 密码哈希:")
    test_password = "MySecretPassword123!"
    hash_result = SensitiveDataHandler.hash_password(test_password)
    print(f"  原始密码: {test_password}")
    print(f"  哈希算法: {hash_result['algorithm']}")
    print(f"  迭代次数: {hash_result['iterations']}")
    print(f"  盐值: {hash_result['salt'][:16]}...")
    print(f"  哈希值: {hash_result['hash'][:32]}...")
    
    # 敏感数据掩码
    print("\n3. 敏感数据掩码:")
    sensitive_text = "password=secret123 api_key=abcd1234567890 email=user@example.com"
    masked_text = SensitiveDataHandler.mask_sensitive_data(sensitive_text)
    print(f"  原始文本: {sensitive_text}")
    print(f"  掩码后: {masked_text}")
    
    # 敏感数据检测
    print("\n4. 敏感数据检测:")
    test_content = """
    # 配置文件
    database_password = "super_secret_123"
    api_key = "sk-1234567890abcdef1234567890abcdef"
    private_key = "-----BEGIN PRIVATE KEY-----"
    """
    detections = SensitiveDataHandler.detect_sensitive_data(test_content)
    for detection in detections:
        print(f"  检测到 {detection['type']}: 第{detection['line']}行")

def demo_secure_command_executor():
    """演示SecureCommandExecutor的使用"""
    print("\n=== SecureCommandExecutor 演示 ===")
    
    # 安全命令执行
    print("\n1. 安全命令执行:")
    safe_commands = ["echo Hello World", "python --version"]
    
    for cmd in safe_commands:
        print(f"\n  执行命令: {cmd}")
        result = SecureCommandExecutor.execute_safe_command(cmd, timeout=10)
        
        if 'error' not in result:
            print(f"  返回码: {result['returncode']}")
            print(f"  输出: {result['stdout'][:100]}...")
            if result['stderr']:
                print(f"  错误: {result['stderr'][:100]}...")
        else:
            print(f"  执行失败: {result['error']}")
    
    # 危险命令被阻止
    print("\n2. 危险命令阻止:")
    dangerous_cmd = "rm -rf /"
    print(f"  尝试执行: {dangerous_cmd}")
    result = SecureCommandExecutor.execute_safe_command(dangerous_cmd)
    print(f"  结果: {result['error'] if 'error' in result else '意外通过'}")

def demo_security_audit():
    """演示security_audit的使用"""
    print("\n=== Security Audit 演示 ===")
    
    # 创建临时目录进行审计
    with tempfile.TemporaryDirectory() as temp_dir:
        print(f"\n对目录进行安全审计: {temp_dir}")
        
        # 创建一些测试文件
        test_files = {
            "config.py": "password = 'secret123'\napi_key = 'sk-abcd1234567890'",
            "script.sh": "#!/bin/bash\necho 'Hello World'",
            "data.txt": "This is normal text content"
        }
        
        for filename, content in test_files.items():
            file_path = os.path.join(temp_dir, filename)
            with open(file_path, 'w') as f:
                f.write(content)
        
        # 执行安全审计
        audit_result = security_audit(temp_dir)
        
        print(f"  审计目录: {audit_result['directory']}")
        print(f"  文件权限问题: {len(audit_result['file_permissions'])}个")
        print(f"  敏感数据发现: {len(audit_result['sensitive_data'])}个")
        print(f"  安全问题: {len(audit_result['security_issues'])}个")
        
        # 显示详细结果
        if audit_result['sensitive_data']:
            print("\n  发现的敏感数据:")
            for item in audit_result['sensitive_data']:
                print(f"    文件: {os.path.basename(item['file'])}")
                for detection in item['detections']:
                    print(f"      - {detection['type']} (第{detection['line']}行)")

def main():
    """主函数"""
    print("安全工具集使用示例")
    print("=" * 50)
    
    try:
        demo_security_validator()
        demo_permission_checker()
        demo_sensitive_data_handler()
        demo_secure_command_executor()
        demo_security_audit()
        
        print("\n" + "=" * 50)
        print("所有演示完成！")
        print("\n使用建议:")
        print("1. 在执行任何系统命令前，使用 SecurityValidator.validate_command() 验证")
        print("2. 在处理文件路径时，使用 SecurityValidator.validate_path() 检查")
        print("3. 在处理用户输入时，使用 SecurityValidator.validate_input() 验证")
        print("4. 在需要管理员权限的操作前，使用 PermissionChecker.check_root_required() 检查")
        print("5. 在处理密码时，使用 SensitiveDataHandler 进行安全处理")
        print("6. 在执行系统命令时，优先使用 SecureCommandExecutor.execute_safe_command()")
        print("7. 定期使用 security_audit() 对重要目录进行安全审计")
        
    except Exception as e:
        print(f"\n演示过程中出现错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()